﻿/* 
* Copyright (c) 2009, SCUT 06级计科2班软件工程第6小组
* All rights reserved. 
*
* 作    者：何伟杰
* 完成日期：2009年7月*日 
*  
* 摘    要：处理用户管理业务逻辑，如注册、登录、找回密码、修改用户资料等
*
* 备    注：用户逻辑并未完全与界面层隔离开，如request对象，以及Render函数
*
*/
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;
namespace SE6
{
    public static class UserMan
    {
		public static String GetUserProfileURL(String name)
		{
			if (name.Length > 0 && name[0] >= '0' && name[0]<='9' && name.IndexOf('.')>0)
				return name;
			else
				return "<a href='DetailProfile.aspx?name=" + HttpUtility.UrlEncode(name) + "' target='_blank'>" +
					name + "</a>";
		}
		//详细信息URL
		public static String GetUserProfileURL(Int32 id)
		{
			return "<a href='DetailProfile.aspx?id=" + id + "'>ID:[" + id + "]</a>";
		}

        public static String ResetPasswordStep1(HttpRequest request, HttpSessionState session)
        {
            String name = Convert.ToString(request.Form["name"]);
            User usr = DAMS.DataAccess.GetUser(name);
            if (usr == null)//用户不存在
                return "";
			SessionMan.SaveResetPasswordUser(usr);
            return usr.Question;
        }
        public static Boolean ResetPasswordStep2(HttpRequest request, HttpSessionState session)
        {
			User usr = SessionMan.GetResetPasswordUser();
			if (usr == null)
				return false;
			String answer = Convert.ToString(request.Form["answer"]);
			String password = Convert.ToString(request.Form["password"]);
			if (answer != null && password != null
				&& usr.ResetPassword(password, answer))
			{
				//更新到数据库
				if (DAMS.DataAccess.Update(usr))
				{
					//清空重置密码的用户
					SessionMan.SaveResetPasswordUser( null);
					return true;
				}
			}			
            return false;
        }
        //用户注册
        public static Boolean Register(HttpRequest request)
        {
            User newUser = CreateFrom(request);
            return DAMS.DataAccess.Insert(newUser);
        }
        //用户登录
        public static String Login(HttpRequest request)
        {			
            String name = Convert.ToString(request.Form["name"]);
			if (Utility.Util.IsEmptyString(name))
				return "用户名不能为空！";
            String password = Convert.ToString(request.Form["password"]);
			if (Utility.Util.IsEmptyString(name))
				return "请先输入密码！";
            User usr = DAMS.DataAccess.GetUser(name);
			if (usr!=null)
			{
				Int32 loginResult = usr.LoginResult(password);
				if (loginResult == -1)//实际上是密码不对
					return "用户名或密码不正确";
				if (loginResult == 1)
					return "您好，您的帐户目前已被禁止登录，有问题请联系管理员或<a href='LeaveMsg.aspx'>留言</a>";
				if (!SystemMan.IsFunctionEnabled(FounctionType.Login) && !usr.IsAdministrator())
					return "系统正在维护中，登陆功能暂时不可用，请稍后再试，谢谢合作！";
				 //&& usr.Login(password)
				usr.Login(password);
				DAMS.DataAccess.Update(usr);
				SessionMan.SaveLoginUser( usr);
				return "";//成功登陆！
			}
			return "用户名或密码不正确！";//实际上是用户不存在
        }
		//修改用户个人信息
		public static String Update(HttpRequest request)
		{
			SE6.User logUsr=SessionMan.GetLoginUser();
			if (logUsr==null)
				return "要更改信息，请先登陆！";
			Int32 id;
			if (!Int32.TryParse((String)request.Form["id"],out id))
				return "您无权限修改该用户信息";
			SE6.User usr=(id==logUsr.ID)?logUsr:(DAMS.DataAccess.GetUser(id));
			if (usr==null)
				return "要修改的用户不存在，或已删除!";
			String email=(String)request.Form["email"];
			if (Utility.Util.IsEmptyString(email))
				email=usr.Email;
			Int32 point;
			if (!Int32.TryParse((String)request.Form["point"],out point) 
				|| !logUsr.IsSuperMan() )//管理员才能修改积分！
				point =usr.Point;				
			usr.Update(email, point);

			if (logUsr.IsSuperMan()&& id!=logUsr.ID)
			{
				Role role=0;
				if (request.Form["bu"] == "on")
					role |= Role.BaseUser;
				if (request.Form["ua"] == "on")
					role |= Role.UploadArchives;
				if (request.Form["da"] == "on")
					role |= Role.DownloadArchives;
				if (request.Form["ua"] == "on")
					role |= Role.UploadArchives;
				if (request.Form["up"] == "on")
					role |= Role.UpdateArchives;
				if (request.Form["dela"] == "on")
					role |= Role.DeleteArchives;
				if (request.Form["lw"] == "on")
					role |= Role.LeaveMessage;
				if (request.Form["lwm"] == "on")
					role |= Role.LeaveWordManager;
				if (request.Form["am"] == "on")
					role |= Role.ArchiveManager;
				if (request.Form["sysm"] == "on")
					role |= Role.SystemManager;
				if (request.Form["god"] == "on")
					role |= Role.God;
				usr.UpdateRole(role);
			}
			if (DAMS.DataAccess.Update(usr))
				return "更新用户信息成功！";
			else
				return "更新用户信息失败，请稍后再试！";
		}
		//用户管理
		public static String ViewUsers(Int32 curPage)
		{
			const Int32 COUNT_PER_PAGE = 10;
			const Int32 PAGE_NAV_COUNT = 10;
			SE6.User curUser = SessionMan.GetLoginUser();
			if (curUser == null)
				return "请先<a href='Login.axpx'>登陆</a>";
			else if (!curUser.IsUserManager())
				return "对不起，您的权限不够，去别的地方玩吧。";
			//Get Matched Count
			Int32 totalCount = DAMS.DataAccess.GetUsersCount();
			PageNav.BoundPage(totalCount, COUNT_PER_PAGE, ref curPage);
			List<User> usrs = DAMS.DataAccess.GetUsers(
				curPage * COUNT_PER_PAGE,
				COUNT_PER_PAGE);
			if (usrs != null)
			{
				Int32 curCount = usrs.Count;
				//生成分页导航
				String sbNav = PageNav.GenNav(totalCount, COUNT_PER_PAGE,
					curPage, PAGE_NAV_COUNT, "?");
				System.Text.StringBuilder sbResult = new System.Text.StringBuilder();
				sbResult.Append("<div class='stat'>当前共有注册用户数<span class='cue'>");
				sbResult.Append(totalCount);
				sbResult.Append("</span>。以下是第<span class='cue'>");
				sbResult.Append((curPage * COUNT_PER_PAGE + 1).ToString());
				sbResult.Append("—");
				sbResult.Append((curPage * COUNT_PER_PAGE + curCount).ToString());
				sbResult.Append("</span>个</div>");
				sbResult.Append(sbNav);
				sbResult.Append("<table cellpadding='0' cellspacing='0'>");
				sbResult.Append(User.RenderHeader());
				Boolean isOdd = false;
				foreach (User usr in usrs)
				{
					sbResult.Append(usr.SimpleRender(isOdd,curPage));
					isOdd = !isOdd;
				}
				sbResult.Append("</table>");
				sbResult.Append(sbNav);
				return sbResult.ToString();
			}
			return "<span class='cue red'>系统出现致命错误！！请报告管理员，谢谢！</span>";
		}
		public static String ViewDetailUser(HttpRequest request)
		{
			Int32 id;
			if (!Int32.TryParse((String)request.QueryString["id"],out id))
			{
				String name=request.QueryString["name"];
				if (!Utility.Util.IsEmptyString(name))
					name = name.Trim();
				id = DAMS.DataAccess.GetUserID(name);
			}
			if (id <= 0)
				return "<span class='cue red>当前查看的用户不存在</span>";
			User logUsr=SessionMan.GetLoginUser();
			User curUsr = (logUsr!=null&&id == logUsr.ID) ? logUsr : DAMS.DataAccess.GetUser(id);
			if (curUsr==null)
				return "<span class='cue red>当前查看的用户不存在</span>";
			return curUsr.Render(logUsr);
		}
		public static String DeleteUser(HttpRequest request)
		{
			SE6.User logUsr = SessionMan.GetLoginUser();
			if (logUsr==null)
				return "您尚未登陆！";
			if (!logUsr.IsUserManager())
				return "对不起，您没有删除用户的权限，系统不响应您的无理要求，去其他地方玩玩吧。";
			Int32 id;
			if (!Int32.TryParse((String)request.QueryString["id"],out id))
				return "操作未完成，您尚未选中任何用户!";
			//TODO:可以优化
			SE6.User usr = DAMS.DataAccess.GetUser(id);
			if (usr == null)
				return "用户不存在，或已被其他管理员删除!";
			if (usr.IsSuperMan())
				return "对方是超级管员用户，您不能对他进行任何操作！";
			if (usr.IsUserManager() && !logUsr.IsSuperMan())
				return "相煎何太急也，对方同样是用户管理员，您不能删除TA，谢谢合作！";
			if (DAMS.DataAccess.DeleteUser(id))
				return "删除用户成功！";
			else
				return "删除用户失败，请稍后再试！";
		}
		public static String ChangeBaseRole(HttpRequest request)
		{
			SE6.User logUsr = SessionMan.GetLoginUser();
			if (logUsr == null)
				return "您尚未登陆！";
			if (!logUsr.IsUserManager())
				return "对不起，您没有更改用户状态的权限，系统不响应您的无理要求，去其他地方玩玩吧。";
			Int32 id;
			if (!Int32.TryParse((String)request.QueryString["id"], out id))
				return "操作未完成，您尚未选中任何用户!";
			if (id == logUsr.ID)
				return "您不能对自己进行操作!";
			SE6.User usr=DAMS.DataAccess.GetUser(id);
			if (usr == null)
				return "该用户已不存在，或被其他管理员删除";
			if (usr.IsSuperMan())
				return "对方是超级管员用户，您不能对他进行任何操作！";
			if (usr.IsUserManager()&&!logUsr.IsSuperMan())
				return "您不能对其他具有管理用户角色的用户进行该操作！";
			usr.ChangeActiveStatus();
			if (DAMS.DataAccess.Update(usr))
				return "操作成功！";
			else
				return "操作失败！请稍后再试！";
		}

        //从request中获取用户输入的注册信息，创建User类
        private static User CreateFrom(HttpRequest request)
        {
            return new User(
                Convert.ToString(request.Form["name"]),
                Convert.ToString(request.Form["password"]),
                Convert.ToString(request.Form["email"]),
                Convert.ToString(request.Form["question"]),
                Convert.ToString(request.Form["answer"]));
        }

    }
}